import 'package:flutter/material.dart';
import 'package:wheel_of_fortune/http/api.dart';
import 'package:wheel_of_fortune/http/wheel_server.dart';
import 'package:wheel_of_fortune/model/address_model.dart';
import 'package:wheel_of_fortune/model/user_address_model.dart';

class ProductProvider extends ChangeNotifier {
  int candyBalance = 0;
  List<UserAddressModel> addressList = [
    UserAddressModel()  // default Registered Address
      ..selectAddress = true 
      ..user = {
        'userName' : 'Jack Chan',
        'phone': '120903892823',
        'address': 'xxx Street, xxx District',
        'cityName': 'jjjj',
        'provinceName': 'mmmmmmmm'
      },
  ];
  initData() {
    getUserLotteryAddress();
  }

  Future<String> giveUpPrize(String id) async {
    try {
      await WheelService().giveUpPrize(id);
      return 'success';
    } catch (e) {
      print('e = $e');
      return 'fail';
    }
  }

  Future collectPrize(String id,
      {String address,
      int cityMunicipalityId,
      String cityName,
      int provinceId,
      String provinceName}) async {
    try {
      await WheelService().collectPrize(
          id, address, cityMunicipalityId, cityName, provinceId, provinceName);
      return 'success';
    } catch (e) {
      return e.toJson();
    }
  }

  getUserLotteryAddress() async {
    try {
      final temp = await WheelService().getUserLotteryAddress();
      addressList.addAll(temp);
    } catch (e) {
      addressList = [];
    }
    notifyListeners();
  }

  selectAddressWithIndex(int index) {
    addressList.forEach((element) {
      element.selectAddress = false;
    });
    if (index >= 0) {
      addressList[index].selectAddress = true;
    }
    notifyListeners();
  }

  editAddress(int index, List list) {
    final data = addressList[index];
    data.address = list[0];
    data.provinceId = (list[1] as ProvinceModel).provinceId;
    data.provinceName = (list[1] as ProvinceModel).provinceName;
    data.cityMunicipalityId = (list[2] as CityModel).cityMunicipalityId;
    data.cityName = (list[2] as CityModel).cityName;
    notifyListeners();
  }

  addAddress(List list) {
    addressList.forEach((element) {
      element.selectAddress = false;
    });
    final data = UserAddressModel();
    data.address = list[0];
    data.provinceId = (list[1] as ProvinceModel).provinceId;
    data.provinceName = (list[1] as ProvinceModel).provinceName;
    data.cityMunicipalityId = (list[2] as CityModel).cityMunicipalityId;
    data.cityName = (list[2] as CityModel).cityName;
    data.selectAddress = true;
    addressList.add(data);
    notifyListeners();
  }
}
